import React, { PureComponent,Fragment } from "react";
import { connect } from "dva";
import router from 'umi/router';
import { Modal, Row, Col, Form, Card, Input, Select, Icon, Button, message, InputNumber} from "antd";
import MaintainPerson from '../../Form/MaintainPerson';
import Upload from "../../../components/Upload";
import RegionalSelection from "../../Form/RegionalSelection";


const FormItem = Form.Item;
const { Option } = Select;
const { TextArea } = Input;

const getBase64 = (img, callback) => {
  const reader = new FileReader();
  reader.addEventListener("load", () => callback(reader.result));
  reader.readAsDataURL(img);
};

const beforeUpload = file => {
  const isJPG = file.type === "image/jpeg" || file.type === "image/png";
  if (!isJPG) {
    message.error("仅允许上传JPG、PNG文件!");
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    message.error("图片文件不能大于2MB!");
  }
  return isJPG && isLt2M;
};



@connect(({ inspection, global }) => ({
  baseUrl:global.baseUrl,
  loading:inspection.loading,
  detaildata:inspection.detaildata,
  dictionaries:global.dictionaries,
  selectSource:global.selectSource,
  // loading: loading.models.equipment_integrated,
}))
@Form.create()
export default class TaskAdd extends PureComponent {
  constructor(props) {
    super(props);
    this.state={
      fileList: [],
    }
  }

  componentDidMount() {
    const { dispatch, match } = this.props;
    const detailId = match.params.id && match.params.id!='detail' ? match.params.id : 0;
    // 维保单位列表
    dispatch({
      type: 'global/fetch_select_maintencompany',
    });
    // // 养护人
    // dispatch({
    //   type: 'global/fetch_select_maintenman',
    // });
    // 区域列表选择
    dispatch({
      type: 'global/fetch_select_district',
    });

    if (detailId) {
        // 编辑时 读取详情
        dispatch({
          type: "inspection/fetch_inspection_info",
          payload: {
            inspectId: detailId
          }
        })
          .then(() => {
            //根据区域id，获取点位数据
            const districtId = this.props.detaildata.districtId;
            this.props.dispatch({
              type: 'global/fetch_select_point',
              payload: {
                districtId,
              }
            })
            //根据维保id，获取相关人员
            const deptId = this.props.detaildata.maintenanceId;
            this.props.dispatch({
              type: 'global/fetch_select_maintenman',
              payload: {
                deptId,
              }
            })
          })
          .then(()=>{
            const {baseUrl} = this.props;
            this.setState({
              fileList:this.props.detaildata.inspectPhoto && this.props.detaildata.inspectPhoto.length>0 ? this.props.detaildata.inspectPhoto.map(item=>{
                item.url = baseUrl+item.url;
                return item;
              }) : []
            })
        })
    }
  }

  // 维保单位关联人搜索事件-------------------------------------
  handleSearchMaintain = ( value ) =>{
    const { dispatch } = this.props;
    const maintenanceId=value.maintenanceId;
    const userId=value.userId;
    const loadData=value.loadData;

    if(userId===0){
      // 清空子节点操作
      dispatch({
        type: 'global/fetch_clear_maintenman',
      })
    }

    if(loadData && maintenanceId!==0){
      // userId!=0 && this.handleChageMaintenance(maintenanceId);
      dispatch({
        type: 'global/fetch_select_maintenman',
        payload: {
          deptId:maintenanceId,
        },
      })
    }
  }
  checkMaintain =  (rule, value, callback) => {
    if (value.userId!==0) {
      callback();
      return;
    }
    callback('请选择维保单位及相关人员');
  }




  handleFormSubmit(e)  {
    e.preventDefault();
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { dispatch, match } = this.props;
        const detailId = match.params.id && match.params.id!='detail' ? match.params.id : 0;
        const action = detailId === 0 ? 'add' : 'edit';

        // if(values.taskTime){
        //   values.beginTime = values.taskTime[0].unix() * 1000;
        //   values.endTime = values.taskTime[1].unix() * 1000;
        // }


        if(values.region && values.region.pointId!==0 && values.region.districtId.length>0){
          values.districtId = values.region.districtId[values.region.districtId.length - 1];
          values.pointId = values.region.pointId;
        }


        if(values.maintenanceInfo && values.maintenanceInfo.maintenanceId!==0 && values.maintenanceInfo.userId!=0){
          values.maintenanceId = values.maintenanceInfo.maintenanceId;
          values.rectifyMan = values.maintenanceInfo.userId;
        }


        dispatch({
          type: `inspection/${action}_inspection`,
          payload: {
            ...values,
            region:undefined,
            maintenanceInfo:undefined,
          }
        }).then(() => {
            this.handleReset();
            message.success(detailId === 0 ? "稽查信息已提交" : "稽查信息已修改");
            this.goBack();
        });
      }
    });
  }

  goBack = () => {
    const { dispatch, location, match } = this.props;
    const detailId = match.params.id && match.params.id!='detail' ? match.params.id : 0;
    if(detailId===0){
      router.push({ pathname:`/inspection/supervise/list`});
    }else{
      router.push({ pathname:`/inspection/supervise/list`,  query: { ...location.query} });
    }
  }

  handleReset = () => {
    const { match } = this.props;
    const detailId = match.params.id && match.params.id!='detail' ? match.params.id : 0;
    this.setState({
      fileList: detailId === 0 ? [] : this.props.detaildata.inspectPhoto ,
    })
    this.props.form.resetFields();
  };



  // 多图上传时间
  handleChangePicUpload = ({ fileList }) => this.setState({ fileList })

  uploadPic = e => {
    if (Array.isArray(e)) {
      return e;
    }
    const filelist =
      e &&
      e.fileList.reduce((arr, current) => {
        if (
          current.response &&
          current.response.data &&
          current.response.data.token
        ) {
          return arr.concat(current.response.data.token);
        } else {
          if (current.status && current.status === "error") {
            return arr.concat([]);
          } else {
            return arr.concat(current.uid);
          }
        }
      }, []);
    return filelist;
  };

  // 安装点位事件-------------------------------------
  handleSearchDistrict = ( value ) =>{
    const { dispatch } = this.props;
    const districtId=value.districtId[value.districtId.length-1];
    const pointId=value.pointId;
    const loadPoint=value.loadPoint;

    if(pointId===0){
      // 清空子节点操作
      dispatch({
        type: 'global/fetch_clear_point',
      })
    }

    if(loadPoint && districtId!=0){
      dispatch({
        type: 'global/fetch_select_point',
        payload: {
          districtId,
        },
      })
    }
  }
  // 用最后个点位检索成数组
  formatDistrictData = (lastid) =>{
    const district=[];
    if(lastid){
      district.unshift(lastid);
      const {selectSource: {districtData} } = this.props;
      const now = districtData.find(item=>item.districtId===lastid);
      if(now && now.parentId!="0"){
        district.unshift(now.parentId);
        this.formatDistrictDataSec(district,now.parentId);
      }
    }
    return district;
  }
  formatDistrictDataSec = (arr,id) =>{
    const {selectSource: {districtData} } = this.props;
    const now = districtData.find(item=>item.districtId===id);
    if(now && now.parentId!="0"){
      arr.unshift(now.parentId);
      this.formatDistrictDataSec(arr,now.parentId);
    }
    return arr;
  }
  checkDistrict =  (rule, value, callback) => {
    if (value.pointId!==0) {
      callback();
      return;
    }
    callback('请选择区域点位!');
  }




  render() {
    const { match, detaildata, dictionaries, selectSource, loading } = this.props;
    const { fileList } = this.state;
    const { getFieldDecorator } = this.props.form;

    const formItemLayout = {
      labelCol: { span: 6 },
      wrapperCol: { span: 18 }
    };

    const detailId = match.params.id && match.params.id!='detail' ? match.params.id : 0;

    console.log('fileList',fileList)

    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );

    return (
       <Card
             // title={ detailId === 0 ? null : `维修单号:${detaildata.inspectionNum}`}
             bodyStyle={{padding:20}}
       >
            {
              (detailId === 0 || (detaildata && detaildata.status=="01")) &&
              <Form layout="horizontal">
                <Row gutter={24}>
                  <Col span={12}>
                    <FormItem {...formItemLayout} label="区域点位" colon={false} >
                      {getFieldDecorator('region',{
                        initialValue: detailId === 0 ? {districtId:[],pointId:0} : {districtId:this.formatDistrictData(detaildata.districtId),pointId:detaildata.pointId},
                        rules: [{required: true, message: "请选择区域点位"},{validator: this.checkDistrict}],
                      })(
                        <RegionalSelection
                          districtData={selectSource.districtData}
                          pointData={selectSource.pointData}
                          onChange={this.handleSearchDistrict}
                        />
                      )}
                    </FormItem>


                    <FormItem {...formItemLayout} label="项目" colon={false}>
                      {getFieldDecorator("inspectProject", {
                        initialValue: detailId === 0 ? undefined : detaildata.inspectProject,
                        rules: [
                          { required: true, message: "请选择项目" },
                        ]
                      })(
                        <Select placeholder="请选择项目"   style={{ width: '100%' }}>
                          {dictionaries.inspectProject && dictionaries.inspectProject.map(item => (
                            <Option key={item.value} value={item.value}>{item.label}</Option>
                          ))}
                        </Select>
                      )}
                    </FormItem>

                    <FormItem {...formItemLayout} label="问题描述" colon={false}>
                      {getFieldDecorator("problemDesc", {
                        initialValue: detailId === 0 ? undefined : detaildata.problemDesc,
                        rules: [{ max: 200, message: "不超过200个字" }]
                      })(
                        <TextArea
                          placeholder="请输入故障描述"
                          autosize={{ minRows: 3, maxRows: 6 }}
                        />
                      )}
                    </FormItem>
                    <FormItem {...formItemLayout} label="维保单位" colon={false}>
                      {getFieldDecorator("maintenanceInfo", {
                        initialValue: detailId === 0 ? {maintenanceId:0,userId:0} : {maintenanceId:detaildata.maintenanceId,userId:detaildata.rectifyMan},
                        rules: [{required: true, message: "请选择维保单位及相关人员"},{validator: this.checkMaintain}],
                      })(
                        <MaintainPerson
                          // span={24}
                          placeholder={"请选择整改人"}
                          maintainData={selectSource.maintenance}
                          personnelData={selectSource.maintenman}
                          onChange={this.handleSearchMaintain}
                        />
                      )}
                    </FormItem>


                    <FormItem {...formItemLayout} label="处理时限" colon={false}>
                      {getFieldDecorator("handleTime", {
                        initialValue: detailId === 0 ? undefined : detaildata.handleTime,
                        rules: [
                          // { required: true, message: "请输入设备名称" },
                        ]
                      })(
                        <InputNumber placeholder="请输入" precision={0}  style={{width:100,marginRight:15}} />
                      )} 小时
                    </FormItem>
                  </Col>


                  <Col span={12}>



                    <FormItem
                      {...formItemLayout}
                      label="上传图片"
                      extra={<span>支持jpg、png<br/>图片大小不超过2M</span>}
                    >
                      {getFieldDecorator("inspectPhotoArray", {
                        valuePropName: "file",
                        getValueFromEvent: this.uploadPic
                      })(
                        <Upload
                          listType="picture-card"
                          fileList={fileList ? fileList : []}
                          // onPreview={this.handlePreview}
                          onChange={this.handleChangePicUpload}
                          beforeUpload={beforeUpload}
                        >
                          {fileList && fileList.length >= 5 ? null : uploadButton}
                        </Upload>
                      )}
                    </FormItem>
                  </Col>

                </Row>

                <Row gutter={24} >
                  <Col span={24} style={{textAlign:'center',padding:30}}>
                    <Button
                      onClick={this.handleFormSubmit.bind(this)}
                      type="primary"
                      size="large"
                      style={{marginRight:15}}
                      loading={loading.model_submit}
                    >
                      提交
                    </Button>
                    <Button
                      onClick={this.handleReset.bind(this)}
                      type="default"
                      size="large"
                    >
                      重置
                    </Button>
                  </Col>
                </Row>
              </Form>
            }
       </Card>
    );
  }
}
